package cms.simmytech.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cms.simmytech.model.SysPermission;
import cms.simmytech.model.SysRole;

import javax.servlet.http.HttpServletRequest;

@Service
public class MyInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {

	@Value("${simmytech.exurl}")
	private String exurl;

	private String pixelUrl;

//	@Autowired
//	private HttpServletRequest request;

	@Autowired
	private UserService userService;

	Log log = LogFactory.getLog(MyInvocationSecurityMetadataSourceService.class);

	@Override
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

		// 获取当前访问url
		String url = ((FilterInvocation) object).getRequestUrl();
		int firstQuestionMarkIndex = url.indexOf("?");
		if (firstQuestionMarkIndex != -1) {
			url = url.substring(0, firstQuestionMarkIndex);
		}
//		pixelUrl=request.getContextPath();
		pixelUrl = ((FilterInvocation) object).getRequest().getContextPath();
		if (!StringUtils.isEmpty(pixelUrl)) {
			url = url.replace(pixelUrl, "");
		}
		if (filter(url)) {
			return null;
		}
		List<ConfigAttribute> result = new ArrayList<>();
		// 查询数据库url匹配的菜单

		List<SysPermission> menuList = userService.getPermissionByUrl(url);
		if (menuList != null && menuList.size() > 0) {
			for (SysPermission menu : menuList) {
				// 查询拥有该菜单权限的角色列表
				List<SysRole> roles = userService.getRoleByPermissionId(menu.getId());
				if (roles != null && roles.size() > 0) {
					for (SysRole role : roles) {
						ConfigAttribute conf = new SecurityConfig(role.getName());
						result.add(conf);
					}
				}
			}
		}
		if (result.isEmpty()) {
			result.add(new SecurityConfig("ROLE_EMPTY"));
		}
		return result;
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

	private boolean filter(String url) {
		String[] urls = exurl.split(",");
		for (String temp : urls) {
			if (url.indexOf(temp) == 0) {
				return true;
			}
		}
		return false;
	}
}
